'use strict';

angular.module('xianwan').factory('Xss', function () {

    let entities = {
        '<': '&lt;',
        '>': '&gt;'
    };

    return {

        filter: function (str) {
            if (!str) {
                return;
            }
            for (let key in entities) {
                str = str.replace(new RegExp(key, 'g'), entities[key]);
            }
            // str = str.replace(new RegExp('\n', 'g'), '<br>');
            str = this.replaceReturn(str);
            return str;
        },

        filterSpecificChar: function (str, chat) {
            let entities = {
                // '&': '&amp;',
                '&': '&#38;'
            }
            if (!entities[chat]) {
                return str;
            }
            return str.replace(new RegExp(chat, 'g'), entities[chat]);
        },

        restore: function (str) {
            if (!str) return '';

            for (let key in entities) {
                if (entities.hasOwnProperty(key)) {
                    str = str.replace(new RegExp(entities[key], 'g'), key);
                }
            }
            return str;
        },

        replaceReturn: function (str) {
            return str.replace(/\n/g, '<br>');
        },

        replaceBr: function (str) {
            return str.replace(/<br>/g, '\n');
        },

        replaceBrByBlank: function (str) {
            return str.replace(/<br>/g, ' ');
        }
        
    }

});